<?php

/*
To delete fucked IDs from user_statistic, using the following SQL, which will delete IDs fucked since '2011-08-15'

create temporary table wasted (select user from (select user, max(collect_date) as last_day from user_statistic group by user) as A where last_day < '2011-08-15');
delete A from user_statistic as A, wasted where A.user = wasted.user;
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

ob_implicit_flush();

require_once '../util.php';
require_once '../config.php';

function get_follow_td($followed, $following, $followed_delta, $following_delta) {
  $percent = $following > 0 ? (number_format(($followed / $following) * 100, 1, '.', '') . '%') : "N/A";
  return sprintf("%s / %s <span style='color:#09F'>%s</span>",
                 format_delta_td($followed, $followed_delta),
                 format_delta_td($following, $following_delta),
                 $percent);
}

function get_date_td($key, $date, $today) {
  if ($key == 0 && $date != $today) {
    return "<td class='date old'>$date</td>";
  } else {
    return "<td class='date'>$date</td>";
  }
}

function get_account_td($key, $info, $count, $url_prefix) {
  if ($key == 0) {
    return sprintf('<a class="delete_account" identity="%s">X</a>%d <a target="_blank" href="%s">%s</a> -- 
<a target="_blank" class="edit_user" href="edit_user.php?identity=%s&user_id=%s">内部</a>',
                   $info['identity'], $count, $url_prefix . $info['local_id'], $info['screen_name'],
                   $info['identity'], $info['id']);
  } else if ($key == 1) {
    return sprintf('<span class="secret" id="%s">%s : %s</span>', $info['id'], $info['identity'], $info['passwd']);
   }
}

function format_delta_td($count, $delta) {
  $td = "<span>" . $count . "</span>";
  if ($delta != 0) {
    $td .= $delta >= 0 ? "<b style='color:#F00'>↑$delta</b>" : "<b style='color:#32CD32'>↓" . abs($delta) ."</b>";
  }
  return $td;
}

function yesterday_stats($user, $limit) {

  $sql = sprintf('select * from user_statistic where user_id="%s" order by collect_date desc limit %d',
                 $user, $limit);

  $ret = mysql_query($sql);
  $arr_stats_data = array();
  while($arr_stats_by_user = mysql_fetch_assoc($ret)){
    $arr_stats_data[] = $arr_stats_by_user;	
  }
  $arr_stats_group = array();

  $size = count($arr_stats_data) == $limit ? count($arr_stats_data) - 1 : count($arr_stats_data);

  if ($size == 0) {
    $arr_stats_group[0]['basic'] = $arr_stats_data[0];
  }
  for ($i = 0; $i < $size; $i++) {
    $arr_stats_group[$i]['basic'] = $arr_stats_data[$i];
    if (isset($arr_stats_data[$i + 1])) {
      $arr_stats_group[$i]['yesterday'] = $arr_stats_data[$i+1];
    } else {
      $arr_stats_group[$i]['yesterday'] = $arr_stats_group[$i]['basic'];
    }
  }
  return $arr_stats_group;
}

$today = date('Y-m-d');
$str_order_by = isset($_GET['orderby']) ? $_GET['orderby'] : 'followed_count';
$limit = isset($_GET['limit'])? $_GET['limit'] : 6;
connect_db();

if (isset($_GET["show-dead"])) {
  $show_dead = True;
  $sql = "select A.user_id from 
(select user_id, max(collect_date) as date, max(followed_count) as followed_count from user_statistic group by user_id) as A 
where A.date <> '$today'
order by A.followed_count desc ";

} else {
  if ($str_order_by == 'followed_count_reverse') {
    $sql = sprintf("select user_id from user_statistic where collect_date = '$today' order by followed_count ");
  } else if ($str_order_by == 'tweet_count_reverse') {
    $sql = sprintf("select user_id from user_statistic where collect_date = '$today' order by tweet_count ");
  } else {
    $sql = sprintf("select user_id from user_statistic where collect_date = '$today' order by %s desc", $str_order_by);
  }
}

$all_user_handle = mysql_query($sql);
if (!$all_user_handle) {
  die("($sql) failed: " . mysql_error());
}
$user_count_in_db = mysql_num_rows($all_user_handle);

?>
  <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
     <link rel="stylesheet" type="text/css" href="css/stats.css" />
     <link rel="stylesheet" type="text/css" href="../css/reset.css">
     <title>taras运行状态</title>
     </head>
     <body>

       <script src="../js/jquery-1.7.1.js"></script>
       <script src="../js/sprintf.js"></script>
       <script src="js/stats.js"></script>
       <div class="content">
         <div class="left_data">
           <table>
             <tr><td><b>功能区</b></td></tr>
             <tr><td>排序类别</td>
               <td>
               <select name="orderby" onchange="condition_by()">
                   <option value="followed_count" <?php if($str_order_by == 'followed_count'){?>selected<?php }?>>粉丝数</option>
                   <option value="followed_count_reverse" <?php if($str_order_by == 'followed_count_reverse'){?>selected<?php }?>>粉丝数倒序</option>
                   <option value="tweet_count" <?php if($str_order_by == 'tweet_count'){?>selected<?php }?>>微博数</option>
                   <option value="tweet_count_reverse" <?php if($str_order_by == 'tweet_count_reverse'){?>selected<?php }?>>微博数倒序</option>
                   <option value="follow_count"  <?php if($str_order_by == 'follow_count'){?>selected<?php }?>>关注数</option>
                   <option value="mutual_follow_count" <?php if($str_order_by == 'mutual_follow_count'){?>selected<?php }?>>互相关注</option>
        	   </select>
               </td></tr>
             <tr><td>limit</td>
               <td>
                 <select name="limit" onchange="condition_by()">
         <?php 
         for ($i = 1; $i <= 10; $i++) {
           echo sprintf('<option value="%d" ', $i, $i);
           if ($limit - 1 == $i) {
             echo 'selected';
           }
           echo ">$i</option>";
         }
         ?>
        	 </select>
               </td></tr>
             <tr><td>
             </td></tr>
           </table>
           <div id="sum-info">
             <?php 
                include "stats-sum-info.php";
             ?>
           </div>
           <?php  echo date('Y-m-d H:i:s'); ?>
         </div>

       <div class="right_data">
       <table class="listing" style="border-collapse:collapse;">
         <tr class="delim">
           <td class="thead">账号</td>
           <td class="thead">粉丝数\关注数(比率)</td>
           <td class="thead">微博数</td>
           <td class="thead">新关注</td>
           <td class="thead">新发文</td>
           <td class="thead">日期</td>
         </tr>

       <?php
           connect_db();
           $ret = mysql_query('select value from core_config where name = "url_prefix";');
           $ret = mysql_fetch_assoc($ret);
           $url_prefix = $ret['value'];

           $account_count = 0;
	   while($arr_result = mysql_fetch_assoc($all_user_handle)){

             $account_count += 1;

             $arr_yesterday_stats = yesterday_stats($arr_result['user_id'], $limit);
          
             $sql = sprintf("select id,identity,passwd from local_user where id='%s'", $arr_result['user_id']);
             $user_info = mysql_query($sql);
             $user_info = mysql_fetch_assoc($user_info);
             $today = date('Y-m-d');
             foreach ($arr_yesterday_stats as $key=>$value){
               $int_followed_dvalue = $value['yesterday']['followed_count']>0?($value['basic']['followed_count'] - $value['yesterday']['followed_count']):0;
               $int_follow_dvalue = $value['yesterday']['follow_count']>0?($value['basic']['follow_count'] - $value['yesterday']['follow_count']):0;
               $int_tweet_count = $value['yesterday']['tweet_count']>0 ? ($value['basic']['tweet_count'] - $value['yesterday']['tweet_count']) : 0;
               $user_info['screen_name'] = $value['basic']['screen_name'];
               $user_info['local_id'] = $value['basic']['local_id'];
               $new_follow = $value['basic']['new_follow'];
               $new_post = $value['basic']['new_post'];
               $date = $value['basic']['collect_date'];

               $date = date('Y-m-d', strtotime($date));

               $cur_row = "";
               // Get cell: account ID
               $cur_row .= "<td class='id-td'>" . get_account_td($key, $user_info, $account_count, $url_prefix) . "</td>";

               // Get cell: follow info
               $cur_row .= "<td class='follow-td'>" . get_follow_td($value['basic']['followed_count'],
                                                                    $value['basic']['follow_count'],
                                                                    $int_followed_dvalue,
                                                                    $int_follow_dvalue) . "</td>";

               // Get cell: tweet count, ommit for now
               $cur_row .= '<td class="tweet">' . format_delta_td($value['basic']['tweet_count'],
                                                                 $int_tweet_count) . "</td>";

               // Get cell: new follow count
               if ($new_follow == 0)
                 $cur_row .= '<td class="small-col"><span class="new_follow" style="border:2px solid red;">' . $new_follow . '</span></td>';
               else
                 $cur_row .= '<td class="small-col"><span class="new_follow">' . $new_follow . '</span></td>';

               // Get cell: new tweet count
               if ($new_post == 0)
                 $cur_row .= '<td class="small-col"><span class="new_post" style="border:2px solid red;">' . $new_post . '</span></td>';
               else
                 $cur_row .= '<td class="small-col"><span class="new_post">' . $new_post . '</span></td>';

               // Get cell: date
               $cur_row .= get_date_td($key, $date, $today);

               if ($key == 0) {
                 $cur_row = "<tr class='first-row'>$cur_row</tr>";
               } else {
                 $cur_row = "<tr>$cur_row</tr>";
               }
               echo $cur_row;
             }
             echo "<tr class='delim'><td></td><td></td><td></td><td></td></tr>";
           }
      ?>
        </table>

        </div>

        </div>
     </body>
  </html>
